package cn.alcatraz.mq_03_oneway;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @Description: 消费者
 * @Author: Alcatraz
 * @Version: 1.0
 * @Date:  2022/7/26 21:09
 */

public class Consumer {

    public static void main(String[] args) throws Exception {
        // 创建消费者，指定消费者组名
        DefaultMQPushConsumer defaultMQPushConsumer = new DefaultMQPushConsumer("oneway_hello_group");

        // 连接nameserver
        defaultMQPushConsumer.setNamesrvAddr("127.0.0.1:9876");

        // 订阅主题
        // topic: 主题
        // subExpression: 主题下的二级分类，填写*获取全部分类
        defaultMQPushConsumer.subscribe("oneway_topic","oneway");

        // 注册监听器
        defaultMQPushConsumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                for (MessageExt messageExt : list) {
                    // 接收消息
                    System.out.println(new String(messageExt.getBody(), StandardCharsets.UTF_8));
                }
                // 标记该消息已经被成功消费
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        // 消费者启动
        defaultMQPushConsumer.start();
    }
}
